// V-backend/src/models/index.js
const { Sequelize, Op } = require('sequelize'); // 添加 Op 导入
require('dotenv').config();

const sequelize = new Sequelize(
  process.env.DB_NAME,
  process.env.DB_USER,
  process.env.DB_PASSWORD,
  {
    host: process.env.DB_HOST,
    port: process.env.DB_PORT,
    dialect: 'mysql',
    logging: console.log,
    timezone: '+08:00',
    pool: {
      max: 10,
      min: 0,
      acquire: 30000,
      idle: 10000
    }
  }
);

// 导入所有模型
const Audience = require('./Audience');
const Anchor = require('./Anchor');
const Activity = require('./Activity');
const Registration = require('./Registration');
const Product = require('./Product');
const ProductImage = require('./ProductImage');
const Cart = require('./Cart');
const Order = require('./Order');
const OrderItem = require('./OrderItem');
const Video = require('./Video');

// 初始化模型
const models = {
  Audience: Audience(sequelize, Sequelize.DataTypes),
  Anchor: Anchor(sequelize, Sequelize.DataTypes),
  Activity: Activity(sequelize, Sequelize.DataTypes),
  Registration: Registration(sequelize, Sequelize.DataTypes),
  Product: Product(sequelize, Sequelize.DataTypes),
  ProductImage: ProductImage(sequelize, Sequelize.DataTypes),
  Cart: Cart(sequelize, Sequelize.DataTypes),
  Order: Order(sequelize, Sequelize.DataTypes),
  OrderItem: OrderItem(sequelize, Sequelize.DataTypes),
  Video: Video(sequelize, Sequelize.DataTypes)
};

// 设置模型关联
Object.values(models).forEach(model => {
  if (model.associate) {
    model.associate(models);
  }
});

// 同步数据库
const syncDatabase = async () => {
  try {
    await sequelize.authenticate();
    console.log('✅ 数据库连接成功');
    
    // 开发环境：关闭自动同步，避免索引限制错误
    if (process.env.NODE_ENV === 'development') {
      console.log('🔧 开发模式：跳过数据库表自动同步');
      // await sequelize.sync({ alter: true });
    } else {
      await sequelize.sync();
      console.log('✅ 数据库表同步完成');
    }
  } catch (error) {
    console.error('❌ 数据库连接失败:', error);
  }
};

syncDatabase();

// 导出 Op 操作符
module.exports = {
  sequelize,
  Sequelize,
  Op, // 导出 Op 供控制器使用
  ...models
};